// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/exec/aggregation_masks.h>
#include <pollux/vector/selectivity_vector.h>

namespace kumo::pollux::exec {

AggregationMasks::AggregationMasks(
    std::vector<std::optional<column_index_t>> maskChannels)
    : maskChannels_{std::move(maskChannels)} {
  for (const auto& maskChannel : maskChannels_) {
    if (maskChannel.has_value()) {
      maskedRows_.insert({maskChannel.value(), SelectivityVector::empty()});
    }
  }
}

void AggregationMasks::addInput(
    const RowVectorPtr& input,
    const SelectivityVector& rows) {
  for (auto& entry : maskedRows_) {
    SelectivityVector& maskedRows = entry.second;
    maskedRows = rows;

    // Get the projection column vector that would be our mask.
    const auto& maskVector = input->childAt(entry.first);
    POLLUX_CHECK_EQ(
        maskVector->type(),
        BOOLEAN(),
        "FILTER(WHERE..) clause must use masks that are BOOLEAN");

    // Get decoded vector and update the masked selectivity vector.
    decodedMask_.decode(*maskVector, rows);
    if (decodedMask_.isConstantMapping()) {
      if (decodedMask_.is_null_at(rows.begin()) ||
          !decodedMask_.value_at<bool>(rows.begin())) {
        maskedRows.setValidRange(rows.begin(), rows.end(), false);
        maskedRows.updateBounds();
      }
    } else {
      rows.applyToSelected([&](vector_size_t i) {
        if (decodedMask_.is_null_at(i) || !decodedMask_.value_at<bool>(i)) {
          maskedRows.setValid(i, false);
        }
      });
      maskedRows.updateBounds();
    }
  }
}

const SelectivityVector* MELON_NULLABLE
AggregationMasks::activeRows(int32_t aggregationIndex) const {
  if (maskChannels_[aggregationIndex].has_value()) {
    auto it = maskedRows_.find(maskChannels_[aggregationIndex].value());
    POLLUX_CHECK(it != maskedRows_.end());
    return &it->second;
  }

  return nullptr;
}
} // namespace kumo::pollux::exec
